package wjh.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import wjh.mapper.wyPatientMapper;
import wjh.pojo.Patient;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class wyPatientServiceImpl implements wyPatientService {
    @Autowired
    private wyPatientMapper patientMapper;
    @Override
    public List<Patient>like(String likename) {
        List<Patient> like = patientMapper.like(likename);
        return like;
    }

    @Override
    public void addPatient(Patient patient, MultipartFile file, HttpServletRequest request) {
                String avatar="default.jpg";
        if(file.getSize()>0){
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String prefix= UUID.randomUUID().toString().replaceAll("-","");
            avatar=prefix+suffix;
            String realPath = request.getServletContext().getRealPath("/static/img/");
            //执行上传
            try {
                file.transferTo(new File(realPath,avatar));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        patient.setAvatar(avatar);
        patientMapper.addPatient(patient);
    }





    @Override
    public List<Patient> findAll() {
        return patientMapper.findAll();
    }

    @Override
    public void deletePatientByid(String ids) {
        String[] idArray = ids.split("-");
        for (String id : idArray) {
            if (!id.isEmpty()) {
                patientMapper.deletePatientByid(String.valueOf(Integer.parseInt(id)));
            }
        }
    }

    @Override
    public Patient findPatientById(int id) {
        return patientMapper.findPatientById(id);
    }

    @Override
    public void updatePatient(Patient patient, MultipartFile file, HttpServletRequest request) {
        String avatar="default.jpg";
        if(file.getSize()>0){
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String prefix= UUID.randomUUID().toString().replaceAll("-","");
            avatar=prefix+suffix;
            String realPath = request.getServletContext().getRealPath("/static/img/");
            //执行上传
            try {
                file.transferTo(new File(realPath,avatar));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        patient.setAvatar(avatar);
        patientMapper.updatePatient(patient);
    }



}
